package com.system.user.controller;


import com.system.common.bean.Admin;
import com.system.common.bean.User;
import com.system.common.service.ILoginService;
import com.system.common.util.Captcha;
import com.system.common.util.Result;
import com.system.common.util.SYS;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/login")
@CrossOrigin
public class LoginController {

    @DubboReference
    ILoginService iLoginService;


    @RequestMapping("/captcha")
    public Result Captcha(){
        return Result.ok(Captcha.getCaptcha());
    }

    @PostMapping("/toUserLogin")
    public Result userLogin(User user, @RequestParam("captcha") String captcha, @RequestParam("key") String key){
        //1.验证码验证
        if (!Captcha.checkCaptcha(key,captcha)){
            return Result.error("验证码错误");
        }
        //2.登录
        try{
            String token = iLoginService.userLogin(user);
            //3.删除验证码

            return Result.ok("登陆成功",token);
        }catch (Exception e){
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("/toAdminLogin")
    public Result adminLogin(Admin admin, @RequestParam("captcha") String captcha, @RequestParam("key") String key){
        //1.验证码验证
        if (!Captcha.checkCaptcha(key,captcha)){
            return Result.error("验证码错误");
        }
        //2.登录
        try{
            String token = iLoginService.adminLogin(admin);
            //3.删除验证码

            return Result.ok("登陆成功",token);
        }catch (Exception e){
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("/loginUserInfo")
    public Result loginUserInfo(HttpServletRequest request) {
        try {
            String token = request.getHeader(SYS.TOKEN_AUTHORIZATION);
            User user = iLoginService.loginUserInfo(token);
            return Result.ok("", user);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("/loginAdminInfo")
    public Result loginAdminInfo(HttpServletRequest request) {
        try {
            String token = request.getHeader(SYS.TOKEN_AUTHORIZATION);
            Admin admin = iLoginService.loginAdminInfo(token);
            return Result.ok("", admin);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
}
